var protocol = global.protocol 
var Package = protocol.Package;
var Message = protocol.Message;

var logger = global.logger

var handlers = {};
var global_request_handler = global.request_handler
var global_notify_handler = global.notify_handler
var ST_INITED = 0;
var ST_WAIT_ACK = 1;
var ST_WORKING = 2;
var ST_CLOSED = 3;

var CODE_OK = 200;
var CODE_USE_ERROR = 500;
var CODE_OLD_CLIENT = 501;

var handleHandshake = function (socket, pkg) {
    console.log(JSON.parse(protocol.strdecode(pkg.body)));
    console.log(socket.state)
    if (socket.state !== ST_INITED) {
        return;
    }

    
    var res = {
        code: CODE_OK,
        sys: {heartbeat:3},
        user: {}
    };
    
    socket.handshakeResponse(Package.encode(Package.TYPE_HANDSHAKE, new Buffer(JSON.stringify(res))));
};

var handleHandshakeAck = function (socket, pkg) {
    if (socket.state !== ST_WAIT_ACK) {
        return;
    }
    socket.state = ST_WORKING;
    socket.heartbeat();
};

var handleHeartbeat = function (socket, pkg) {
    if (socket.state !== ST_WORKING) {
        return;
    }
    socket.heartbeat();
};

var handleData = function (socket, pkg) {
    if (socket.state !== ST_WORKING) {
        return;
    }
    var msg = Message.decode(pkg.body)
    var msgdata = JSON.parse(protocol.strdecode(msg.body))

    if(msg.type == Message.TYPE_REQUEST){
        if(global_request_handler[msg.route]){
            global_request_handler[msg.route](socket, msgdata, msg.id)
        }
        else{
            logger.error('could not find request handle: ' + msg.route);
        }
    }
    else if(msg.type == Message.TYPE_NOTIFY){
        if(global_notify_handler[msg.route]){
            global_notify_handler[msg.route](socket, msgdata)
        }
        else{
            logger.error('could not find notify handle: ' + msg.route);
        }
    }
    //socket.emit('message', pkg);
};

handlers[Package.TYPE_HANDSHAKE] = handleHandshake;
handlers[Package.TYPE_HANDSHAKE_ACK] = handleHandshakeAck;
handlers[Package.TYPE_HEARTBEAT] = handleHeartbeat;
handlers[Package.TYPE_DATA] = handleData;

var handle = function (socket, pkg) {
    var handler = handlers[pkg.type];
    if (!!handler) {
        handler(socket, pkg);
    } else {
        logger.error('could not find handle invalid data package.');
        socket.disconnect();
    }
};

module.exports = handle;
